<template>
  <div class="inventory-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>采购入库
      </el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索商品名称"
        prefix-icon="Search"
        clearable
        style="width: 230px; margin-left: 20px"
      />
      <el-select
        v-model="searchType"
        placeholder="按类型筛选"
        clearable
        style="width: 150px; margin-left: 10px"
        @change="handleTypeSelect"
      >
        <el-option label="肉类" value="肉类" />
        <el-option label="蔬菜" value="蔬菜" />
        <el-option label="水产" value="水产" />
        <el-option label="调料" value="调料" />
        <el-option label="粮食" value="粮食" />
        <el-option label="其他" value="其他" />
      </el-select>
      <el-button type="primary" style="margin-left: 10px" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button type="default" style="margin-left: 10px" @click="resetSearch">
        重置筛选
      </el-button>
    </div>

    <el-table :data="inventoryList" style="width: 100%" border>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="商品名称" width="150" />
      <el-table-column prop="type" label="商品类型" width="120" />
      <el-table-column prop="quantity" label="库存数量" width="120">
        <template #default="scope">
          <span :class="{ 'low-stock': scope.row.quantity < 10 }">{{ scope.row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑库存对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '采购入库' : '编辑库存'"
      width="500px"
    >
      <el-form :model="inventoryForm" :rules="rules" ref="inventoryFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="inventoryForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-select v-model="inventoryForm.type" placeholder="请选择商品类型" style="width: 100%">
            <el-option label="肉类" value="肉类" />
            <el-option label="蔬菜" value="蔬菜" />
            <el-option label="水产" value="水产" />
            <el-option label="调料" value="调料" />
            <el-option label="粮食" value="粮食" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="quantity">
          <el-input-number v-model="inventoryForm.quantity" :min="0" :precision="0" :step="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="inventoryForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="inventoryForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)  // 初始化为0，避免显示不准确

// 搜索关键词
const searchKeyword = ref('')
// 搜索类型
const searchType = ref('')

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.timeout = 10000

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 打印响应数据，帮助调试
    console.log('API响应数据:', response.data)
    return response
  },
  error => {
    console.error('API请求错误:', error)
    ElMessage.error('请求失败，请检查网络连接')
    return Promise.reject(error)
  }
)

// 库存列表
const inventoryList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const inventoryFormRef = ref<FormInstance>()
const inventoryForm = reactive({
  id: 0,
  name: '',
  type: '',
  quantity: 0,
  unit: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择商品类型', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ]
}

// 入库/出库相关代码已移除

// 从后端获取库存数据
const fetchInventoryList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 打印请求参数
    console.log('发送筛选请求，参数：', {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchKeyword.value,
      type: searchType.value
    })
    
    // 调用后端API获取库存列表
    const response = await axios.get('/inventory/page', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        name: searchKeyword.value,
        type: searchType.value
      }
    })

    console.log('收到筛选响应:', response.data)

    if (response.data.code === 1) {
      // 更新库存列表和总数
      inventoryList.value = response.data.data.records || []
      total.value = response.data.data.total || 0

      // 如果后端没有返回总数，但有返回记录，则使用记录数量作为总数
      if (total.value === 0 && inventoryList.value.length > 0) {
        total.value = inventoryList.value.length
      }

      console.log('筛选后库存数据:', inventoryList.value)
      console.log('筛选后总记录数:', total.value)
    } else {
      ElMessage.error(response.data.msg || '获取库存列表失败')
    }
  } catch (error) {
    console.error('获取库存列表出错:', error)
    ElMessage.error('获取库存列表失败，请稍后再试')
  } finally {
    loading.close()
  }
}

// 类型筛选 - 专用函数处理类型筛选
const handleTypeSelect = (value: string) => {
  console.log('类型选择变化，当前值:', value)
  // 重置到第一页
  currentPage.value = 1
  // 立即触发筛选
  fetchInventoryList()
}

// 搜索库存 - 处理搜索按钮点击
const handleSearch = () => {
  console.log('点击搜索按钮，关键词:', searchKeyword.value, '类型:', searchType.value)
  currentPage.value = 1 // 重置为第一页
  fetchInventoryList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  searchType.value = ''
  currentPage.value = 1 // 重置为第一页
  fetchInventoryList()
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchInventoryList()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchInventoryList()
}

// 新增库存
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑库存
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  resetForm()
  Object.assign(inventoryForm, row)
  dialogVisible.value = true
}

// 入库和出库功能已移除

// 删除库存
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除商品"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 调用后端API删除库存
      const response = await axios.delete('/inventory', {
        params: {
          ids: row.id.toString()  // 修改为字符串，避免方括号编码问题
        }
      })

      if (response.data.code === 1) {
        ElMessage.success('删除成功')
        fetchInventoryList() // 重新加载库存列表
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除库存出错:', error)
      ElMessage.error('删除失败，请稍后再试')
    } finally {
      loading.close()
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  if (inventoryFormRef.value) {
    inventoryFormRef.value.resetFields()
  }
  inventoryForm.id = 0
  inventoryForm.name = ''
  inventoryForm.type = ''
  inventoryForm.quantity = 0
  inventoryForm.unit = ''
  inventoryForm.remark = ''
}

// 入库/出库表单重置函数已移除

// 提交表单
const submitForm = async () => {
  if (!inventoryFormRef.value) return

  await inventoryFormRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '提交中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        if (dialogType.value === 'add') {
          // 新增库存
          const response = await axios.post('/inventory', {
            name: inventoryForm.name,
            type: inventoryForm.type,
            quantity: inventoryForm.quantity,
            unit: inventoryForm.unit,
            remark: inventoryForm.remark,
            merchantId: 1 // 假设当前商家ID为1
          })

          if (response.data.code === 1) {
            ElMessage.success('采购入库成功')
            fetchInventoryList() // 重新加载库存列表
          } else {
            ElMessage.error(response.data.msg || '采购入库失败')
          }
        } else {
          // 编辑库存
          const response = await axios.put('/inventory', {
            id: inventoryForm.id,
            name: inventoryForm.name,
            type: inventoryForm.type,
            quantity: inventoryForm.quantity,
            unit: inventoryForm.unit,
            remark: inventoryForm.remark
          })

          if (response.data.code === 1) {
            ElMessage.success('编辑成功')
            fetchInventoryList() // 重新加载库存列表
          } else {
            ElMessage.error(response.data.msg || '编辑失败')
          }
        }
        dialogVisible.value = false
      } catch (error) {
        console.error('提交库存数据出错:', error)
        ElMessage.error('操作失败，请稍后再试')
      } finally {
        loading.close()
      }
    }
  })
}

// 入库/出库表单提交函数已移除
// 组件挂载时加载数据
onMounted(() => {
  // 从后端获取库存数据
  fetchInventoryList()
})
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}
</style>
